package k2paltform.common.util;

import org.apache.avro.Schema;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by ming on 16-9-8.
 */
public class AvroUtil {

    public static boolean isSensorField(Schema.Field field) {
        return !(field.name().equals(Constants.SCHEMA_TIMESTAMP) || field.name().equals(Constants.SCHEMA_FGSYSID) || AvroUtil.isIdField(field));
    }

    //another way is to check name is started with id_. (if sensor field, started with s_)
    public static boolean isIdField(Schema.Field field) {
        if(field.getObjectProp(Constants.SCHEMA_IDFIELD_ISKEY) != null) {
            if(field.getObjectProp(Constants.SCHEMA_IDFIELD_ISKEY) instanceof Boolean)
                return (boolean)field.getObjectProp(Constants.SCHEMA_IDFIELD_ISKEY);
            else
                return false;
        }
        else
            return false;
    }

    public static String[] getIdFields(Schema schema) {
        List<String> idFieldList = new ArrayList<>();
        for(Schema.Field field : schema.getFields()) {
            if(AvroUtil.isIdField(field)) {
                for(String alia : field.aliases()) {
                    idFieldList.add(alia);
                    break;
                }
            }
        }
        return idFieldList.toArray(new String[idFieldList.size()]);
    }

    public static String[] getIdFieldSysIds(Schema schema) {
        List<String> idFieldList = new ArrayList<>();
        for(Schema.Field field : schema.getFields()) {
            if(AvroUtil.isIdField(field))
                idFieldList.add(field.name());
        }
        return idFieldList.toArray(new String[idFieldList.size()]);
    }

    public static String getFieldGroupId(Schema schema) {
        if(schema != null) {
            String namespace = schema.getNamespace();
            Set<String> aliases = schema.getAliases();
            for(String aliase : aliases) {
                return aliase.substring(namespace.length() + 1);
            }
        }
        return null;
    }

    public static String getFirstAlia(Schema.Field field) {
        if(field.aliases().size() < 1)
            return null;

        for(String alia : field.aliases()) {
            return alia;
        }
        return null;
    }
}
